//购物车tab类型承载页
var app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx');
Page({
  data: {
    isLocate: true,
    isLogin: true,
    showPhonePop: false,
    showLoginPop: false,
    isDisableLog: false,
    isDisableReg:false,
    zgList: [], //到家购物车列表
    djList: [], //专供购物车列表
    djCartNum: '',
    zgCartNum: '',
    listType: 2, //1默认查询专供，2查询到家
    addressInfo: [],
    location: "",
    goodIds: [], //获取推荐位的索引商品id
    isDeliverable: "",
    curStore: "",
    logoMtop: 20
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  onShow: function() {
    if (app.globalData.sdkversion > 210 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      wx.setBackgroundColor({
        backgroundColor: '#F5F5F5', // 顶部窗口的背景色为
        backgroundColorBottom: '#F5F5F5' // 底部窗口的背景色为白色
      })
      this.setData({
        logoMtop: wx.getMenuButtonBoundingClientRect().top == 0 ? 20 : wx.getMenuButtonBoundingClientRect().top
      })
    }
    wx.hideTabBarRedDot({
      index: 1
    });
    this.setData({
      isLocate: app.globalData.isLocate,
      listType: app.globalData.cartIndexType == 0 ? 2 : app.globalData.cartIndexType
    })
    if (this.data.isLocate) {
      this.getUserInfo();
    }
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      this.setData({
        isLocate: true
      })
      this.getUserInfo();
    } else {
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  switchTab(e) {
    this.setData({
      listType: e.currentTarget.dataset.id
    })
    app.globalData.cartIndexType = e.currentTarget.dataset.id;
    this.getList();
  },

  getUserInfo() {
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        this.setData({
          isLogin: true,
          showPhonePop: false,
          showLoginPop: false
        })
        this.getList();
      },
      fail: res => {
        this.checkRegister();
      }
    })
  },

  checkRegister() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          this.setData({
            isLogin: false
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {
              this.getList();
            }
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          isLogin: false
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  showLoginPop() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          this.setData({
            showPhonePop: true
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          this.setData({
            tel: res.data.member.cellphone,
            ticketsnum: res.data.coupon_num,
            avatar: res.data.avatar
          })
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {
              this.getList();
            }
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },

  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false,
      isLogin: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../common/agreement',
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  showCheckTel() {
    this.setData({
      showPhonePop: false
    })
    wx.navigateTo({
      url: '../common/register',
    })
  },
  getPhoneNumber: function(e) {
    this.setData({
      isDisableReg:true
    })
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
      this.setData({
        isDisableReg: false
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code
          }, res => {
            if (res.data.errno == '0') {
              that.setData({
                isLogin: true,
                isDisableReg: false
              })
              that.getList();
              that.storageUserinfo(res.data.data)
            } else {
              this.setData({
                isDisableReg: false
              })
              common.showErrorToast(res.data.errmsg);
            }
          })
        },
        fail:res=>{
          this.setData({
            isDisableReg: false
          })
        }
      })
    }
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isLogin: true,
        isDisableLog: false
      })
      this.checkRegister();
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  getList() {
    if (this.data.listType == 1) {
      this.getZgCart();
      this.getCartNum();
    } else {
      app.globalData.isFromCart = true;
      this.setData({
        location: app.globalData.location
      })
      this.data.curStore = wx.getStorageSync('storeId');
      if (app.globalData.addrId == null || app.globalData.addrId == "undefined" || app.globalData.location == null) {
        this.getCartByLonLa();
      } else {
        this.setData({
          location: app.globalData.location
        })
        var param = {
          "address_id": app.globalData.addrId,
          "longitude": "",
          "latitude": "",
          "store_id": this.data.curStore,
          "city": app.globalData.city,
          "selected": app.globalData.addrId == null ? "store" : "address"
        }
        this.getDjCartList(param);
      }
    }
  },
  //获取专供购物车列表
  getZgCart() {
    server.postJSON(common.storePath + 'eventcart/index', '', res => {
      if (res.data.errno == '0') {
        wx.hideLoading();
        var goods = res.data.data;
        if (goods.length > 0) {
          for (var i = 0; i < goods.length; i++) {
            goods[i].selectedNum = 0;
            goods[i].lackNum = 0;
            if (goods[i].goods.length > 0) {
              for (var j = 0; j < goods[i].goods.length; j++) {
                goods[i].goods[j].isCanAdd = true;
                goods[i].goods[j].isCanReduce = true;
                goods[i].goods[j].style = "";
                if (goods[i].goods[j].is_selected == "1") {
                  goods[i].selectedNum++;
                }
                if (goods[i].goods[j].is_lack == 1) {
                  goods[i].lackNum++;
                }
              }
              if (goods[i].selectedNum == goods[i].goods.length) {
                goods[i].isSelectAll = true;
              } else {
                goods[i].isSelectAll = false;
              }
              if (goods[i].lackNum == goods[i].goods.length) {
                goods[i].showSelectAll = false;
              } else {
                goods[i].showSelectAll = true;
              }
            }
            this.setData({
              zgList: goods
            })
          }
        } else {
          this.setData({
            zgList: []
          })
        }
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  //获取到家购物车列表
  getDjCartList(param) {
    param.store_id = param.store_id == 0 ? '' : param.store_id;
    server.postJSON(common.storePath + 'cart/index/', param, res => {
      if (res.data.errno == "0") {
        common.hideLoading();
        var goods = res.data.data.goods;
        goods[0].selectedNum = 0;
        goods[0].lackNum = 0;
        if (goods[0].list.length > 0) {
          for (var j = 0; j < goods[0].list.length; j++) {
            goods[0].list[j].isCanAdd = true;
            goods[0].list[j].isCanReduce = true;
            goods[0].list[j].style = "";
            if (goods[0].list[j].is_selected == "1") {
              goods[0].selectedNum++;
            }
            if (goods[0].list[j].is_lack == 1) {
              goods[0].lackNum++;
            }
            this.data.goodIds.push(goods[0].list[j].goods_id);
          }
          this.data.curStore = goods[0].store_id;
          this.data.curRecommendStoreId = goods[0].service_store_id>0&&goods[0].service_type=='entity'?goods[0].service_store_id:goods[0].store_id;
          this.data.isDeliverable = goods[0].is_deliverable;
          this.getCartNum();
          this.getRecommendGoods();
          if (goods[0].selectedNum == goods[0].list.length) {
            goods[0].isSelectAll = true;
          } else {
            goods[0].isSelectAll = false;
          }
          if (goods[0].lackNum == goods[0].list.length) {
            goods[0].showSelectAll = false;
          } else {
            goods[0].showSelectAll = true;
          }
        } else {
          this.setData({
            recommendGoods: []
          })
        }
        this.setData({
          addressInfo: res.data.data.address.length == 0 ? [] : [res.data.data.address],
          djList: goods
        })
        wx.setStorage({
          key: 'storeId',
          data: goods[0].store_id,
        })
      } else {
        this.setData({
          djList: [],
          addressInfo: []
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //根据经纬度获取到家购物车列表
  getCartByLonLa() {
    if (app.globalData.longitude != null && app.globalData.latitude != null && app.globalData.location != null) {
      var param = {
        "address_id": app.globalData.addrId,
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude,
        "store_id": this.data.curStore,
        "city": app.globalData.city,
        "selected": app.globalData.addrId == null ? "store" : "address"
      }
      this.setData({
        location: app.globalData.location
      })
      this.getDjCartList(param);
    } else {
      var gdMap = new amapFile.AMapWX({
        key: common.gdKey
      });
      gdMap.getRegeo({
        success: res => {
          app.globalData.locateLongitude = res[0].longitude;
          app.globalData.locateLatitude = res[0].latitude;
          app.globalData.locateCity = res[0].regeocodeData.addressComponent.city;
          app.globalData.city = res[0].regeocodeData.addressComponent.city;
          app.globalData.locateProvince = res[0].regeocodeData.addressComponent.province;
          app.globalData.location = res[0].regeocodeData.pois[0] == undefined ? res[0].name : res[0].regeocodeData.pois[0].name;
          app.globalData.longitude = res[0].longitude;
          app.globalData.latitude = res[0].latitude;
          this.setData({
            location: res[0].regeocodeData.pois[0] == undefined ? res[0].name : res[0].regeocodeData.pois[0].name
          })
          var param = {
            "address_id": app.globalData.addrId,
            "longitude": app.globalData.longitude,
            "latitude": app.globalData.latitude,
            "store_id": this.data.curStore,
            "city": app.globalData.city,
            "selected": app.globalData.addrId == null ? "store" : "address"
          }
          this.getDjCartList(param);
        },
        fail: info => {
          common.showErrorToast('定位中...')
        }
      })
    }
  },
  //根据地址获取到家购物车
  getCartByAddrId() {
    var param = {
      "address_id": app.globalData.addrId,
      "longitude": "",
      "latitude": "",
      "store_id": "",
      "city": app.globalData.city,
      "selected": "address"
    }
    this.getDjCartList(param);
  },
  //获取到家推荐位
  getRecommendGoods() {
    if (this.data.goodIds.length > 0) {
      server.postJSON(common.storePath + 'store/getrecommendgoods/', {
        "store_id": this.data.curRecommendStoreId,
        "recommend_type": 'buy_to_buy',
        "recommend_num": 10,
        "goods_ids": this.data.goodIds
      }, res => {
        if (res.data.errno == '0') {
          if (res.data.data.length > 0) {
            (res.data.data).forEach((item, index) => {
              item.isCanAdd = true;
              item.isCanReduce = true;
            })
            this.setData({
              recommendGoods: res.data.data
            })
            if (common.compareVersion(wx.getSystemInfoSync().SDKVersion, '1.9.6') >= 0) {
              this.data.recommendGoods.forEach((item, idx) => {
                let intersect = wx.createIntersectionObserver();
                intersect.relativeToViewport().observe('#easy-rec-' + item.goods_id, (res) => {
                  intersect.disconnect(); //使用disconnect，使得目标节点只曝光一次
                  console.log('曝光#easy-rec-' + item.goods_id);
                  server.postJSON(common.storePath + 'store/reportusertrace/', {
                    "store_id": this.data.curStore,
                    "recommend_type": 'buy_to_buy',
                    "list": [{
                      "goods_id": item.goods_id,
                      "trace_id": item.trace_id,
                      "position": idx
                    }]
                  }, res => {
                    if (res.data.errno == '0') {
                      console.log('曝光成功')
                    } else {
                      common.showErrorToast(res.data.errmsg)
                    }
                  })
                })
              })
            }
          }else{
            this.setData({
              recommendGoods:[]
            })
          }
        } else {
          common.showErrorToast(res.data.errmsg)
        }
      })
    }

  },
  //添加为你推荐商品
  addRecommendCart(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      ['recommendGoods[' + index + '].isCanAdd']: false
    })
    server.postJSON(common.storePath + 'cart/addgoods/', {
      "store_id": this.data.curStore,
      "goods_id": e.currentTarget.dataset.id,
      "trace_id": e.currentTarget.dataset.traceid,
      "scene": "buy_to_buy"
    }, res => {
      if (res.data.errno == "0") {
        common.showErrorToast('添加成功');
        this.setData({
          cartNum: parseInt(this.data.cartNum) + 1,
          ['recommendGoods[' + index + '].isCanAdd']: true,
          ['recommendGoods[' + index + '].cart_num']: parseInt(this.data.recommendGoods[index].cart_num) + 1
        })
        this.getCartByLonLa();
      } else {
        this.setData({
          ['recommendGoods[' + index + '].isCanAdd']: true
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //组件查询购物车
  getDjCartListByChild(param) {
    this.getDjCartList(param.detail)
  },
  //获取购物车数量
  getCartNum() {
    server.postJSON(common.storePath + 'cart/goodsnum', {
      "store_id": this.data.curStore == '' ? 0 : this.data.curStore,
      "is_deliverable": this.data.isDeliverable
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          djCartNum: res.data.data.cart.num,
          zgCartNum: res.data.data.event.num
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  backPrev(){
    wx.navigateBack();
  }
})